from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django import forms

from .models_software import Software, SoftwareLicense


class SoftwareForm(forms.ModelForm):
    class Meta:
        model = Software
        fields = ["name", "vendor", "category", "description"]


class SoftwareLicenseForm(forms.ModelForm):
    class Meta:
        model = SoftwareLicense
        fields = [
            "software",
            "license_key",
            "seats",
            "start_date",
            "end_date",
            "status",
            "supplier",
            "notes",
        ]


# Software CRUD
@login_required
@permission_required('assets.view_software', raise_exception=True)
def software_list(request):
    q = (request.GET.get('q') or '').strip()
    qs = Software.objects.all()
    if q:
        qs = qs.filter(Q(name__icontains=q) | Q(vendor__icontains=q) | Q(category__icontains=q))
    paginator = Paginator(qs.order_by('name'), 20)
    page_obj = paginator.get_page(request.GET.get('page'))
    return render(request, 'assets/software/software_list.html', {
        'page_obj': page_obj,
        'query': q,
    })


@login_required
@permission_required('assets.add_software', raise_exception=True)
def software_create(request):
    if request.method == 'POST':
        form = SoftwareForm(request.POST)
        if form.is_valid():
            obj = form.save()
            messages.success(request, '软件已创建')
            return redirect('assets:software_detail', pk=obj.pk)
    else:
        form = SoftwareForm()
    return render(request, 'assets/software/software_form.html', {'form': form, 'form_action': 'create'})


@login_required
@permission_required('assets.view_software', raise_exception=True)
def software_detail(request, pk):
    obj = get_object_or_404(Software, pk=pk)
    licenses = obj.licenses.all().order_by('-created_at')[:20]
    return render(request, 'assets/software/software_detail.html', {'software': obj, 'licenses': licenses})


@login_required
@permission_required('assets.change_software', raise_exception=True)
def software_update(request, pk):
    obj = get_object_or_404(Software, pk=pk)
    if request.method == 'POST':
        form = SoftwareForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            messages.success(request, '软件已更新')
            return redirect('assets:software_detail', pk=obj.pk)
    else:
        form = SoftwareForm(instance=obj)
    return render(request, 'assets/software/software_form.html', {'form': form, 'software': obj, 'form_action': 'edit'})


@login_required
@permission_required('assets.delete_software', raise_exception=True)
def software_delete(request, pk):
    obj = get_object_or_404(Software, pk=pk)
    if request.method == 'POST':
        name = obj.name
        obj.delete()
        messages.success(request, f'软件 {name} 已删除')
        return redirect('assets:software_list')
    return render(request, 'assets/software/software_confirm_delete.html', {'software': obj})


# Software License CRUD
@login_required
@permission_required('assets.view_softwarelicense', raise_exception=True)
def license_list(request):
    q = (request.GET.get('q') or '').strip()
    qs = SoftwareLicense.objects.select_related('software', 'supplier').all()
    if q:
        qs = qs.filter(Q(software__name__icontains=q) | Q(license_key__icontains=q))
    paginator = Paginator(qs.order_by('-created_at'), 20)
    page_obj = paginator.get_page(request.GET.get('page'))
    return render(request, 'assets/software/license_list.html', {
        'page_obj': page_obj,
        'query': q,
    })


@login_required
@permission_required('assets.add_softwarelicense', raise_exception=True)
def license_create(request):
    if request.method == 'POST':
        form = SoftwareLicenseForm(request.POST)
        if form.is_valid():
            obj = form.save()
            messages.success(request, '许可已创建')
            return redirect('assets:license_detail', pk=obj.pk)
    else:
        initial = {}
        if (sid := request.GET.get('software')):
            initial['software'] = sid
        form = SoftwareLicenseForm(initial=initial)
    return render(request, 'assets/software/license_form.html', {'form': form, 'form_action': 'create'})


@login_required
@permission_required('assets.view_softwarelicense', raise_exception=True)
def license_detail(request, pk):
    obj = get_object_or_404(SoftwareLicense, pk=pk)
    return render(request, 'assets/software/license_detail.html', {'license': obj})


@login_required
@permission_required('assets.change_softwarelicense', raise_exception=True)
def license_update(request, pk):
    obj = get_object_or_404(SoftwareLicense, pk=pk)
    if request.method == 'POST':
        form = SoftwareLicenseForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            messages.success(request, '许可已更新')
            return redirect('assets:license_detail', pk=obj.pk)
    else:
        form = SoftwareLicenseForm(instance=obj)
    return render(request, 'assets/software/license_form.html', {'form': form, 'license': obj, 'form_action': 'edit'})


@login_required
@permission_required('assets.delete_softwarelicense', raise_exception=True)
def license_delete(request, pk):
    obj = get_object_or_404(SoftwareLicense, pk=pk)
    if request.method == 'POST':
        obj.delete()
        messages.success(request, '许可已删除')
        return redirect('assets:license_list')
    return render(request, 'assets/software/license_confirm_delete.html', {'license': obj})
